package com.bac.rentmap.ad.flat.rating;

import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.bac.rentmap.ad.flat.FlatAd;
import com.bac.rentmap.jdo.JdoSupport;

public class JdoBetterFlatAdProvider extends JdoSupport implements
		BetterFlatAdProvider {
	private static final Logger log = Logger
			.getLogger(JdoBetterFlatAdProvider.class.getName());

	@Override
	public int countFlatAdsWithBetterRating(String city, long rating) {
		log.fine("Counting FlatAds with rating better (greater) than " + rating);
		PersistenceManager persistenceManager = getPersistenceManager();
		try {
			Query query = persistenceManager.newQuery(FlatAd.class);
			query.setFilter("city == cityParam && rating > ratingParam");
			query.declareParameters("String cityParam, String ratingParam");

			query.setResult("count(this)");
			Object res = query.execute(city, rating);
			if(res == null)
			    res = 0;
			log.info(res + " FlatAds has better rating than " + rating);
			return ((Number) res).intValue();
		} finally {
			persistenceManager.close();
		}
	}

}
